import { ipcMain, dialog } from 'electron'
import { resolve } from 'path'
import wallpaper from 'wallpaper'
import fetch from 'node-fetch'
import { createWriteStream } from 'node:fs'
import { pipeline } from 'node:stream'
import { promisify } from 'node:util'
import fs from 'fs'
const downloadFile = async (url, localFile) => {
  const streamPipeline = promisify(pipeline)
  const response = await fetch(url)

  if (!response.ok) {
    dialog.showErrorBox('后盾人温馨提示', '图片下载失败')
    throw new Error(`unexpected response ${response.statusText}`)
  }
  await streamPipeline(response.body, createWriteStream(localFile))
  return localFile
}

ipcMain.on('setWallpaper', async (event, url, path) => {
  try {
    const localFile = resolve(path, url.split('/').pop())
    const file = await downloadFile(url, localFile)
    wallpaper.set(file, { screen: 'all', scale: 'auto' })
  } catch (error) {
    dialog.showErrorBox('设置壁纸失败，请检查网络')
  }
})
ipcMain.on('downloadImage', async (event, url) => {
  const fileName = url.split('/').pop()
  const res = await dialog.showSaveDialog({
    title: '下载目录',
    defaultPath: fileName,
    properties: ['createDirectory']
  })
  if (!res.canceled && res.filePath.length) downloadFile(url, res.filePath)
})

ipcMain.handle('checkDirectory', async (event, path) => {
  return fs.existsSync(path)
})

ipcMain.handle('setImageDirectory', async () => {
  const res = await dialog.showOpenDialog({
    title: '选择图片保存目录',
    properties: ['createDirectory', 'openDirectory']
  })
  if (!res.canceled && res.filePaths.length) {
    return res.filePaths[0]
  }
  return undefined
})
